package SGNet2

import (
	"net"
	"time"
)

//Session 每一个客户端对应一个客户的会话
type Session struct {
	ID       int64
	Conn     net.Conn
	Server   *NetServer
	in       chan interface{}
	out      chan interface{}
	UserData interface{}
}

//Send 向客户端发送消息
func (sess *Session) Send(datas ...interface{}) {
	if sess == nil {
		return
	}
	data, err := sess.Server.Protocol.Send(datas...)
	if err != nil {
		Log("SGNet2,Error", err)
		return
	}

	sess.out <- data
}

func (sess *Session) receive() {
	for {
		retData, err := sess.Server.Protocol.Receive(sess.Conn)
		if err != nil {
			Log("SGNet2,Error", err)

			return
		}
		Log("Server,Server.DetailInfo", "Data", retData)
		select {
		case sess.in <- retData:
		case <-time.After(60 * time.Second):
			Log("Error,Server", "Session写入数据失败")
			return
		}
	}

}

func (sess *Session) agent() {
	defer sess.Close()
	for {
		select {
		case data, ok := <-sess.in:
			if !ok {
				return
			}
			Log("Server.DetailInfo", "agent data", data)
			sess.Server.Protocol.DispatchPacket(sess, data)
		case outData := <-sess.out:
			sess.Conn.Write(outData.([]byte))
		}
	}
}

func (sess *Session) loop() {
	defer sess.Close()
	go sess.agent()
	sess.receive()
}

//Close 关闭会话
func (sess *Session) Close() {
	sess.Server.RemoveSession(sess)
	sess.Conn.Close()
	Log("Server.DetailInfo,Server", "一个Session(", sess.ID, ")断开了连接 当前连接的Session数:[", len(sess.Server.Sessions), "]")
}
